package com.rc.saas.tenant.common.sms;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.fluent.Request;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 短信发送工具
 */
public class SmsUtil {
    private static org.slf4j.Logger logger= LoggerFactory.getLogger(SmsUtil.class);

    private static final String ACCESS_URL="http://sms.10690221.com:9011/hy/";
    private static final String UID="81079";
    private static final String MD5_AUTH="9c793f56603a7b914befe0ebe127c7fe";//16进制

    /**
     * 执行发送短信(详见http://www.sioo.com.cn/APIdoc/smssend.html)
     * @param mobile 发送手机
     * @param content 发送内容(不得超过603字符,推荐末尾添加空格或标点以和实际短信后的按T退订隔开)
     * @return 发送结果,null为无响应失败,有响应为响应代码(0成功)
     */
    public static String sendSms(String mobile,String content){
        if (StringUtils.isBlank(mobile)){
            return null;
        }
        List<NameValuePair> list=new ArrayList<>();
        list.add(new BasicNameValuePair("uid",UID));
        list.add(new BasicNameValuePair("auth",MD5_AUTH));
        list.add(new BasicNameValuePair("mobile", mobile));
        try {
            list.add(new BasicNameValuePair("msg", URLEncoder.encode(content,"gbk")));
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
            throw new RuntimeException();
        }
        list.add(new BasicNameValuePair("expid","0"));
        try {
            return Request.Post(ACCESS_URL).bodyForm(list).execute().handleResponse(new ResponseHandler<String>() {
                @Override
                public String handleResponse(HttpResponse httpResponse) throws IOException {
                    int code=httpResponse.getStatusLine().getStatusCode();
                    logger.info(""+code);
                    if (code != 200) {
                        return null;
                    }
                    String result= EntityUtils.toString(httpResponse.getEntity());
                    return result.substring(0,result.indexOf(","));
                }
            });
        } catch (IOException e) {
            logger.error("执行发送短信error:",e);
            return null;
        }
    }

    private SmsUtil() {}
}
